<?php
defined('EXEC') or die();
$transacao = 'fluxo_caixa';

if(!$auth->isRead($transacao)){
	Util::info(Config::AUTH_MESSAGE);
	return true;
}
//Importando a classes
Loader::import('com.atitudeweb.SQL');
////////////////////////
//CRUD atitudeweb 1.0 //
////////////////////////
$form 			= false;
$rowEdit 		= array();
$tableEdit 		= "tethys.tb_extrato_conta ec left join tethys.tb_titulos tt on ec.cd_titulo=tt.ci_titulo left join tethys.tb_tipo_documento td on tt.cd_tipo_documento=td.ci_tipo_documento left join tethys.tb_forma_pagamento fp on tt.cd_forma_pagamento=fp.ci_forma_pagamento";
$updateTable    = "tethys.tb_extrato_conta";
$tablepk 		= 'ci_extratoconta';
$limitPagina 	= 10; //Registros por página
$faixa 			= 10; //Faixa de páginas que irão ser mostradas paginação (google)
$dif 			= 5; //A diferença que a faixa de páginas irão começar a caminhar (google)
$p 				= (@$_GET['p'] ? $_GET['p'] : 1);
$id_update      = @$_POST['id_update'];
$id_insert      = @$_POST['id_insert'];
$aberto         = @$_POST['hdn_aberto'];
$pago           = @$_POST['hdn_pago'];
$cancelado      = @$_POST['hdn_cancelado'];
$pesquisar      = @$_POST['btSearch'];
$color          = 0;


$search1 =(@$_POST['search1']);

$fields=" tt.ci_titulo, td.nm_tipo_documento||'-'||tt.nr_documento as nm_documento,to_char(dt_pagamento,'dd/mm/yyyy') as dt_pagamento,
	   td.ci_tipo_documento, td.nm_tipo_documento,tt.nr_documento as nr_documento, to_char(tt.dt_cadastro,'dd/mm/yyyy') as dt_cadastro, fp.ci_forma_pagamento,fp.ds_forma_pagamento,
       to_char(tt.dt_emissao,'dd/mm/yyyy') as dt_emissao, to_char(tt.dt_vencimento,'dd/mm/yyyy') as dt_vencimento,
      trim(to_char(tt.vlr_documento::numeric,'R$99G999D99')) AS vlr_documento,trim(to_char(coalesce(ec.vlr_documento,tt.vlr_pago)::numeric,'R$999G999D99'))as vlr_pago, tt.multa,tt.juros, tt.desconto,trim(to_char(tt.vlr_documento::numeric,'99G999D99')) as valor, tt.tipo_titulo,tt.obs,tt.fl_status";

//Adicionando js para picklist
Controller::addHead('jquery.picklists', 'js');
Controller::addHead('jquery.multiselects-0.3', 'js');

//checa se existe caixa aberto caso nao redireciona para pagina principal
$ChecaCaixa ="select coalesce(count(ci_mov_caixa),0) as cx_aberto from tethys.tb_movimento_caixa where  dt_fechamento is null";
$rs = Connection::query($ChecaCaixa);
$row = $rs->fetch();

if ($row['cx_aberto'] != 1) {
	$page="index.php";
	Controller::setInfo('Fluxo de Caixa e Banco', 'Realize primeiro a abertura de caixa!', 'danger', '', 3500);
	Controller::redirect($page);
}
//Mudança do formulário para adição ou alteração de registro
if(isset($_GET['form'])){
	if($_GET['form'] == 0){
		$btFormLabel = 'Adicionar';
	}
	else{
		$btFormLabel = 'Salvar';
		$rowEdit = SQL::getRowsByFields($tableEdit, array($tablepk => $_GET['form']), null,  true, null, null, $fields, null);
	}
	$form = true;
}

//Consulta no banco e mecânica de paginação
if($pesquisar=='P' || !$form){
	$where = " 1=1 and";

	if(isset($_POST['search1']) && (!empty($_POST['search1'])) ){
		$term = addslashes($_POST['search1']);
		if (!empty($term)){
			$where .=  " ci_titulo ={$term} and ";}
	}
	if(isset($_POST['search2']) && (!empty($_POST['search2'])) ){
		$term = addslashes($_POST['search2']);
		if (!empty($term)){
			$where .=  " nr_documento= {$term} and ";}
	}
	if(isset($_POST['search3']) && (!empty($_POST['search3'])) ){
		$term = addslashes($_POST['search3']);
		if (!empty($term)){
			$where .=  " ci_cliente= {$term} and ";}
	}
	if(isset($_POST['search4']) && (!empty($_POST['search4'])) ){
		$term = addslashes($_POST['search4']);
		if (!empty($term)){
			$where .=  " to_char(dt_emissao,'dd/mm/yyyy')='{$term}' and ";}
	}
	if(isset($_POST['search5']) && (!empty($_POST['search5'])) ){
		$term = addslashes($_POST['search5']);
		if (!empty($term)){
			$where .=  " to_char(dt_vencimento,'dd/mm/yyyy')='{$term}' and ";}
	}
	if(isset($_POST['search6']) && (!empty($_POST['search6'])) ){
		$term = addslashes($_POST['search6']);
		if (!empty($term)){
			$where .=  " vlr_documento={$term} and ";}
	}

	if(isset($_POST['search7']) && (!empty($_POST['search7'])) ){
		$term = addslashes($_POST['search7']);
		if (!empty($term)){
			$where .=  " to_char(dt_pagamento,'dd/mm/yyyy')='{$term}' and ";}
	}

	//Verifica qual check está marcado para adicionar na consulta
	if( !empty($aberto) && !empty($pago) && !empty($cancelado)){
		$cond .=" (  fl_status={$aberto} or fl_status={$pago} or fl_status={$cancelado} ) and ";
			
	}elseif( !empty($aberto) && !empty($pago) && empty($cancelado)){
		$cond .=" ( fl_status={$aberto} or fl_status={$pago} ) and ";
			
	}elseif( !empty($aberto) && !empty($cancelado) && empty($pago) ){
		$cond .=" ( fl_status={$aberto} or fl_status={$cancelado} ) and ";
			
	}elseif( !empty($pago) && !empty($cancelado) && empty($aberto)){
		$cond .="( fl_status={$pago} or fl_status={$cancelado} ) and";
			
	}elseif( !empty($aberto) && empty($pago) && empty($cancelado)){
		$cond .=" ( fl_status={$aberto} ) and ";
			
	}elseif( !empty($pago) && empty($aberto) && empty($cancelado)){
		$cond .=" ( fl_status={$pago} ) and ";
			
	}elseif( !empty($cancelado) && empty($aberto) && empty($pago)){
		$cond =" ( fl_status={$cancelado} ) and ";
	}

	$where .= @$cond ;

	if($where != ''){
		$where = "where ".substr($where, 0, -4);
	}

	$sql=" select $fields from $tableEdit $where
		   limit {$limitPagina} offset ".(($p - 1) * $limitPagina);	
	 
	//echo $sql;
	//die;
	$query = query($sql);
	$sqlNum = " select count(*) as num from $tableEdit $where";
	$rowNum = query($sqlNum)->fetch();
	$registros = $rowNum['num'];

	$paginacao = Util::pagination($registros, 4);
}
?>
<h3>
	<i class="glyphicon glyphicon-user"></i> Fluxo de Caixa -
	<?php echo (!isset($_GET['form']) ? 'Pesquisa' : (@$_GET['form'] > 0 ? 'Edição' : 'Cadastro')); ?>
</h3>
	<?php if(!isset($_GET['form'])){ ?>
<a
	href="#" class="command-page"
	onclick="window.location='?page=financeiro/controle_caixa';"></a>
	<?php } ?>

<div class="panel panel-default">
	<div class="panel-body">
		<div id="alerts"></div>
		<?php if(!isset($_GET['form'])){ ?>
		<form action="<?php echo Util::setLink(array('p=null')); ?>"
			method="post" class="form">
			<div class="row">
				<div class="col-md-4">
					<div class="form-group">
						<label class="control-label">Data Inicial:</label>
						<div class="input-group date" id="datepicker_inicio">
							<input type="text" name="search4" id="search4"
								class="form-control" value="<?php echo @$_POST['search4']; ?>"
								data-format="DD/MM/YYYY" onkeypress="mask(this, data)"
								maxlength="10" readonly="readonly" /> <span
								class="input-group-addon btn btn-default"><span
								class="glyphicon glyphicon-calendar"></span>
						
						</div>
					</div>
				</div>
				<div class="col-md-4">
					<div class="form-group">
						<label class="control-label">Data Final:</label>
						<div class="input-group date" id="datepicker_fim">
							<input type="text" name="search5" id="search5"
								class="form-control" value="<?php echo @$_POST['search5']; ?>"
								data-format="DD/MM/YYYY" onkeypress="mask(this, data)"
								maxlength="10" readonly="readonly" /> <span
								class="input-group-addon btn btn-default"><span
								class="glyphicon glyphicon-calendar"></span>
						
						</div>
					</div>
				</div>
				<div class="col-md-2">
					<div class="form-group">
						<button id="btSearch" class="btn btn-default btn-adjust">
							<span class="fa fa-search"></span> Consultar
						</button>
					</div>
				</div>
			</div>
		</form>
		<?php } ?>
	</div>

	<form method="post" id="formSearch">
		<div class="table-responsive">
			<input type="hidden" id="hdn_radio" name="hdn_radio" />
			<table
				class="table table-striped table-bordered table-hover table-condensed">
				<thead>
					<tr class="ui-widget-header">
						<th>Cód.</th>
						<th>Documento</th>
						<th>Data de Emissão</th>
						<th>Data de Vencimento</th>
						<th>Data de Pagamento</th>
						<th>Valor</th>
						<th>Valor Rcebido</th>
						<th>Multa</th>
						<th>Juros</th>
						<th>Desconto</th>
					</tr>
				</thead>
				<tbody>
				<?php
				if($pesquisar=='P'){
					$count = 0;
					while($rowEdit = $query->fetch()){
						if ($rowEdit['fl_status']=='R'){
							$color="color:green;";
						}
				 	elseif($rowEdit['fl_status']=='C'){
				 		$color="color:red;text-decoration: line-through;";

				 	}elseif($rowEdit['fl_status']=='A'){
				 		$color="color:blue;";
				 	}
				 	echo '<tr style="'.$color.'" >
		            	<td>'.$rowEdit['ci_titulo'].'</td>
						<td>'.$rowEdit['nm_documento'].'</td>		                
		                <td>'.$rowEdit['dt_emissao'].'</td>
		                <td>'.$rowEdit['dt_vencimento'].'</td>
		                <td>'.$rowEdit['dt_pagamento'].'</td>
		                <td>'.$rowEdit['vlr_documento'].'</td>
		                <td>'.$rowEdit['vlr_pago'].'</td>	
      				    <td>'.$rowEdit['multa'].'</td>	
      				    <td>'.$rowEdit['juros'].'</td>							
      				    <td>'.$rowEdit['desconto'].'</td>					
		        	</tr>';
				 	$count++;
					}
				}?>
				</tbody>
			</table>
		</div>
	</form>
	<?php echo $paginacao; ?>
	<?php  ?>
</div>



<style type="text/css">
.overlay {
	visibility: hidden;
	position: absolute;
	left: 20%;
	top: 30%;
	width: 55%;
	height: 38%;
	text-align: left;
	z-index: 1000;
	background-color: #CCC;
}

ul.none {
	list-style-type: none;
	display: inline;
}

#funcoes ul {
	padding: 0px;
	margin: 0px;
	float: left;
	width: 100%;
	background-color: #EDEDED;
	list-style: none;
}

#funcoes ul li {
	display: inline;
}

#funcoes ul li a {
	padding: 2px 10px;
	float: left;
	/* visual do link */
	background-color: #EDEDED;
	color: #333;
	text-decoration: none;
	border-bottom: 3px solid #EDEDED;
}

#funcoes ul li a:hover {
	background-color: #D6D6D6;
	color: #6D6D6D;
	border-bottom: 3px solid #EA0000;
}
</style>


<script type="text/javascript"> 

$("#datepicker_inicio").datetimepicker({
	pickTime:false,
	language:'pt-br'
});

$("#datepicker_fim").datetimepicker({
	pickTime:false,
	language:'pt-br'
});


$("#search3").change(function(){
		//alert($(this).val());
	$("#loading").ajaxStart(function(){
	   $(this).show();
	 });
	$.ajax({
			url: "consultas/getCliente.php",
			type: "POST",
			data: { ci_cliente:$(this).val()},
			dataType: "json",
			success: function(json){
				//alert(json.logradouro);
				$("#loading").ajaxStop(function(){
				   $(this).hide();
				 });
				$('#nm_pessoa').val(json.nm_cliente);
			}					
	});
});		

$("#cd_pessoa2").change(function(){
		//alert($(this).val());
	$("#loading").ajaxStart(function(){
	   $(this).show();
	 });
	$.ajax({
			url: "consultas/getCliente.php",
			type: "POST",
			data: { ci_cliente:$(this).val()},
			dataType: "json",
			success: function(json){
				//alert(json.logradouro);
				$("#loading").ajaxStop(function(){
				   $(this).hide();
				 });
				$('#nm_pessoa1').val(json.nm_cliente);
			}					
	});
});			

$(function()
{
    $("#simple").pickList({
    	sourceListLabel:    "",
        targetListLabel:    "",
        addAllLabel:        "Adicionar Todos",
        addLabel:           "Adicionar",       
        removeLabel:        "Remover",
        removeAllLabel:     "Remover Todos",
        sortAttribute:      "value"	        
    });

});

$(function() {
	$( "#search4" ).datepicker({
		showOn: "button",
		buttonImage: "assets/calendar.png",
		buttonImageOnly: true
	});
});
$(function() {
	$( "#search5" ).datepicker({
		showOn: "button",
		buttonImage: "assets/calendar.png",
		buttonImageOnly: true
	});
});
$(function() {
	$( "#search7" ).datepicker({
		showOn: "button",
		buttonImage: "assets/calendar.png",
		buttonImageOnly: true
	});
});
$(function() {
	$( "#dt_emissao" ).datepicker({
		showOn: "button",
		buttonImage: "assets/calendar.png",
		buttonImageOnly: true
	});
});
$(function() {
	$( "#dt_vencimento" ).datepicker({
		showOn: "button",
		buttonImage: "assets/calendar.png",
		buttonImageOnly: true
	});
});

</script>
